#include "groupusermodel.hpp"
#include "db.h"

bool GroupUserModel::insert(int groupid, int userid, string role){
    char sql[1024] = {0};
    sprintf(sql,"insert into chat_groupuser(groupId,userId,grouprole) values(%d,%d,'%s')",groupid,userid,role.c_str());

    MySQL mysql;
    if(mysql.connect()){
        if(mysql.update(sql)){
            return true;
        }
    }
    return false;
}

bool GroupUserModel::remove(int groupid, int userid){
    char sql[1024] = {0};
    sprintf(sql,"delete from chat_groupuser where groupId = %d and userId = %d",groupid,userid);

    MySQL mysql;

    if(mysql.connect()){
        if(mysql.update(sql)){
            return true;
        }
    }
    return false;
}

vector<int> GroupUserModel::queryGroupAllUsers(int userid, int groupid){

    char sql[1024] = {0};
    sprintf(sql,"select cgu.userId from chat_groupuser cgu where cgu.groupId = %d and cgu.userId != %d",groupid,userid);

    vector<int> users;
    MySQL mysql;
    if(mysql.connect()){
        MYSQL_RES* res = mysql.query(sql);
        if(res != nullptr){
            MYSQL_ROW row;
            while((row = mysql_fetch_row(res)) != nullptr){
                users.push_back(atoi(row[0]));
            }
        }
        mysql_free_result(res);
    }
    return users;
}